﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace GN.Pay.Utils
{
    /// <summary>
    /// Xml 帮助
    /// </summary>
    public static class XmlUtils
    {



        /// <summary>
        /// 加载 Xml 
        /// </summary>
        /// <param name="xmlString">xml字符</param>
        /// <param name="rootElement">根元素</param>
        /// <returns></returns>
        public static IDictionary<string, object> LoadXmlString(string xmlString,
            string rootElement)
        {
            ExceptionUtils.CheckNotNullOrNotWhiteSpace(xmlString, nameof(xmlString));
            ExceptionUtils.CheckNotNullOrNotWhiteSpace(rootElement, nameof(rootElement));
            XDocument document = XDocument.Parse(xmlString);
            IDictionary<string, object> elementDic = new Dictionary<string
                , object>(StringComparer.InvariantCultureIgnoreCase);
            var element = document.Element(rootElement);
            if (element != null)
            {
                foreach (var e in element.Elements())
                {
                    LoadXmlString(elementDic, e);
                }
            }
            return elementDic;
        }

        private static void LoadXmlString(IDictionary<string, object> elementDic,
            XElement xElement)
        {
            if (xElement.Elements().Count() > 0)
            {
                IDictionary<string, object> subDic = new Dictionary<string
                , object>(StringComparer.InvariantCultureIgnoreCase);
                foreach (var e in xElement.Elements())
                {
                    LoadXmlString(subDic, e);
                }
                elementDic[xElement.Name.ToString()] = subDic;
            }
            else {
                elementDic[xElement.Name.ToString()] = xElement.Value;
            }
        }
    }
}
